import numpy as np

from interpolation import newton_interpolate
from utils import random_samples,uniform_samples, chebyshev_nodes, calculate_average_error, plot_interpolation_comparison

# 标准函数

def rational_function(x):
    x = np.array(x)
    return 1 / (25 * x ** 2 + 1)

#################### 可调节参数 ############################

# 设置插值区间
interval = [-1, 1]
# 设置样本点数量
num_samples = 16
# 设置实验点数量
num_experiments = 1000

sampling_method_list = ["uniform", "chebyshev", "random"]
# 设置采样方式
sampling_method = sampling_method_list[1]  # 可选

function_type_list = ["rational"]


################### end #############################################

custom_function = rational_function
    

# 生成样本点
if sampling_method == "random":
    x_samples = random_samples(interval[0], interval[1], num=num_samples)
elif sampling_method == "chebyshev":
    x_samples = chebyshev_nodes(interval[0], interval[1], num=num_samples)
elif sampling_method == "uniform":
    x_samples = uniform_samples(interval[0], interval[1], num=num_samples)
else:
    raise ValueError("Invalid sampling method.")

y_samples = custom_function(x_samples)

# 生成实验点
x_experiment = uniform_samples(interval[0], interval[1], num=num_experiments)

# 计算标准函数在实验点的真实值
y_true = custom_function(x_experiment)

# 打印实验设置
print(f"Experiment Setup:")
print(f"Sampling Method: {sampling_method.capitalize()}")
print(f"Interval: {interval}")
print(f"Number of Samples: {num_samples}")
print(f"Number of Experiments: {num_experiments}")

print("Starting interpolation...")

interpolation_results = {
        "Newton": newton_interpolate(x_samples, y_samples, x_experiment),
    }

errors = {}
for method, y_interp in interpolation_results.items():
    average_error = calculate_average_error(y_true, y_interp)
    errors[method] = average_error

# 输出插值方法的平均误差
print("Average Errors:")
for method, error in errors.items():
    print(f"{method}: {error}")

# 作图
plot_interpolation_comparison(x_experiment, y_true, interpolation_results, x_samples, y_samples)